<template>
	<div class="box" style="background: #fff;overflow: hidden;padding: 10px;">
		<!-- 表单 -->
		<van-cell-group>
			<van-field :value="obj.invoiceName" placeholder="发票名称" :border="false" :readonly="isLook" label="发票名称"
				input-align='right' @change="changeInput($event , 'invoiceName')" />

			<van-field :value="obj.money" placeholder="请输入报销金额" :readonly="isLook" type="digit" :border="false"
				label="金额" input-align='right' @change="changeInput($event , 'money')" />

			<van-field :value="obj.createTime" placeholder="请输入创建日期"  readonly :border="false"
				label="创建日期" input-align='right' @change="changeInput($event , 'createTime')" />

			<van-field :border="false" label="报销凭证" readonly center input-align='right' v-if="!isLook">
				<van-uploader @after-read="afterRead" slot="button" accept='all' :disabled="isLook">
					<button type="primary" class="uploadEvidence">上传凭证</button>
				</van-uploader>
			</van-field>

			<div class="fileList">
				<p v-for="(item,index) in obj.fileList" :key="index" >
					<span @click='lookFile(item)' class="span1">
						{{item.fileName}}
					</span>
					
					<span  v-if="!isLook" class="span2">
						<van-icon  name="edit" size="14px" @click='upDateFileName(item , index)' />
						
						<van-icon  name="cross" style="margin-left: 10px;" size="14px"
							@click='delFile(item , index)' />
					</span>
				</p>
			</div>


			</van-field>

		</van-cell-group>

		<button class="save" @click="save" v-if="!isLook">保存</button>

		<!-- 输入文件名称 -->
		<van-popup :show="isShowFileNameInput" @close='isShowFileNameInput = false' position="center" round>
			<div class="fileNameInput">
				<van-field :value="fileObj.fileName" placeholder="文件名称" :border="false" type="textarea" autosize
					:disabled="isLook" label="发票名称" input-align='right' @change="e => fileObj.fileName = e.detail" />

				<button class="save" @click="saveFile" style="margin-top: 10px;">确定</button>
			</div>
		</van-popup>

	</div>


</template>

<script>
	export default {
		data() {
			return {
				obj: {
					fileList: [],
					taskType: '0',
					taskTypeName: '未报销',
					expenseType: '',
					theSameDay: '1'
				},
				selectList: [],
				selectChange: '',
				selectObj: {},
				str: '',
				isShowTimeSection: false, // 选择时间弹出框
				isShowTimeSection1: false, // 选择时间弹出框
				userInfo: {},
				minHour: 0,
				maxHour: 23,
				isLook: false,
				fileObj: {},
				isShowFileNameInput: false // 输入文件名称的弹出框

			}
		},

		onLoad(option) {
			if (option.id) {
				if (option.isLook) this.isLook = option.isLook
				this.$axios('overallSituation', {
					state: 'look',
					databaseName: "applyForReimbursement",
					_id: option.id
				}, true).then(res => {
					this.obj = res.data[0]
				})

			} else {
				this.userInfo = uni.getStorageSync('userInfo')
				this.obj.userName = this.userInfo.userName
				this.obj.createTime = this.processingTime()
			}

		},

		methods: {
			// 保存按钮
			async save() {
				let result = await this.$axios('overallSituation', {
					state: this.obj._id ? 'update' : 'add',
					databaseName: "applyForReimbursement",
					...this.obj
				}, true)

				if (result.code == 200) {
					uni.navigateBack({
						delta: "1"
					})
				}

			},

			// 时分秒点击确定
			onConfirm(e) {
				console.log(e);
				// 如果开始 结束时间都没有值 默认给 开始时间赋值
				if (!this.obj.startTime) {
					this.obj.startTime = this.processingTime() + " " + e.detail
					this.minHour = new Date(this.obj.startTime).getHours()
				} else {
					// 如果开始时间有值 赋值给结束时间
					this.obj.endTime = this.processingTime() + " " + e.detail
				}

				// 判断某一项是否有值
				if (!this.obj.endTime) {
					uni.showToast({
						title: "请选择结束时间",
						icon: "none",
						duration: 2000
					})
				} else if (!this.obj.startTime) {
					uni.showToast({
						title: "请选择开始时间",
						icon: "none",
						duration: 2000
					})
				} else {
					this.isShowTimeSection1 = false
					this.obj.startAndEndTime = this.obj.startTime + "~" + this.obj.endTime
				}

			},

			// 选择框发生变化
			changeInput(e, str) {
				this.selectChange = this.obj[str]
				this.obj[str] = e.detail
			},





			// 点击选择时间区间
			showTimeSection() {
				if (this.isLook) return
				this.isShowTimeSection = true
			},

			// 点击报销起止日
			timeSection() {
				if (this.isLook) return
				this.isShowTimeSection = true

			},

			// 查看附件
			lookFile(row) {
				uni.showLoading({
					title: "正在打开附件",
				})
				uni.downloadFile({
					url: row.fileUrl,
					success: res => {
						console.log(res, 'res');
						if (res.statusCode == '200') {
							uni.hideLoading()
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true,
								success() {
									console.log("打开成功");
								},
								fail() {
									console.log('打开失败');
								}
							})
						}
					}
				})
			},

			// 选择时间
			onConfirmTime(e) {
				console.log(e);
				// 处理时间格式
				this.obj.startTime = this.processingTime(e.detail[0])
				this.obj.entTime = this.processingTime(e.detail[1])
				this.obj.startAndEndTime = this.obj.startTime + '~' + this.obj.entTime
				this.obj.startAndEndTimeList = e.detail
				console.log(this.obj);
				this.isShowTimeSection = false
			},

			// 文件上传成功 / 处理文件上传的逻辑
			async afterRead(e) {
				this.fileObj = e.detail.file

				// 弹出输入文件名称的弹框
				uni.showLoading({
					title: "文件上传中...",
				})

				let obj = {
					fileName: this.fileObj.name,
					fileUrl: this.fileObj.url,
					fileSize: (this.fileObj.size / 1024 / 1024).toFixed(2)
				}

				// 将地址转为线上的
				let imageRes = await uniCloud.uploadFile({
					filePath: this.fileObj.url,
					cloudPath: this.fileObj.name,
					header: {
						"Content-Type": "multipart/form-data"
					},
				})

				this.isShowFileNameInput = false

				uni.hideLoading()

				obj.fileUrl = imageRes.fileID

				this.obj.fileList.push(obj)

			},

			// 修改文件名称
			upDateFileName(row, index) {
				this.fileObj = row
				this.isShowFileNameInput = true
			},
				
			// 修改文件名保存
			saveFile() {
				if(!this.getFileExtension(this.fileObj.fileName)){
					uni.showToast({
						title:'请补充文件后缀',
						icon:'none',
						duration:2000
					})
					return
				}
				
				this.isShowFileNameInput = false
			},

			// 截取文件后缀
			getFileExtension(fileName) {
				// 查找最后一个 '.' 的位置
				const dotIndex = fileName.lastIndexOf('.');

				// 如果没有找到 '.' 或者它在字符串的开始位置，则返回空字符串
				if (dotIndex === -1 || dotIndex === 0) {
					return '';
				}

				// 从 '.' 位置到字符串结束的部分就是扩展名
				return fileName.substring(dotIndex);
			},

			// 删除已上传文件
			delFile(row, index) {
				uni.showModal({
					title: '提示',
					content: '您确定删除这条报销凭证吗？',
					confirmText: "确定", //这块是确定按钮的文字
					cancelText: "取消", //这块是取消的文字
					success: (res) => {
						if(!res.confirm) return
						this.obj.fileList.splice(index, 1)
					},
				})
			},


			// 获取报销类型
			async getProjectType() {
				let result = await this.$axios('overallSituation', {
					databaseName: 'dataDictionaryDetail',
					state: 'look',
					identification: 'bxlx',
				}, true)

				if (result.code == 200) {
					this.selectList = result.data
				}
			},


			processingTime(value) {
				let date;
				if (value) {
					date = new Date(value)
				} else {
					date = new Date()
				}

				let year = date.getFullYear().toString()
				let month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1) 
				let day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()

				let result = year + '-' + month + '-' + day

				return result
			}
		}
	}
</script>

<style scoped>
	.save {
		width: 97%;
		height: 35px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		background: #e03131;
		margin-top: 20px;
		font-size: 12px;
	}

	.fileList {
		margin-top: 10px;
		padding: 10px;
		box-sizing: border-box;
	}

	.fileList p {
		margin: 5px 0;
		color: #333;
		font-size: 12px;
		display: flex;
		align-items: center;
		padding: 10px 0;
		box-sizing: border-box;
		border-bottom: 1px solid #bac8ff;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	
	.fileList p .span1 {
		width: 85%;
		overflow: hidden;/* //溢出隐藏 */
		word-break: keep-all;
		white-space: nowrap; /* //文本不折行 */
		text-overflow: ellipsis;/* //显示省略符号来代表被修剪的文本。 */
	}
	
	.fileList p .span2 {
		flex: 1;
		text-align: right;
	}

	.fileNameInput {
		width: 95vw;
		height: 200px;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
	
	.uploadEvidence {
		padding: 2px 10px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		color: #fff;
		background-color: #fa5252;
		
	}
	
</style>